#!/usr/bin/python
#-*-coding:utf-8-*-
import server.ccl_server as server
import constant.constant_value as constant
import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

user_access_tokens = {} # access_token的本地缓存，防止多次登录后的次数限制

def get_access_token(username,password):
    access_token = "";
    if user_access_tokens.has_key(username): # 先找本地缓存
        date,access_token = user_access_tokens[username]
        if ((datetime.datetime.now() - date).days < 25) :
            return access_token;
    
    url = constant.api_url_domain+constant.api_url_access_token+"&username="+username.encode("gbk",'ignore')+"&password="+password;
    #print url
    values = {}
    values['client_id'] = constant.api_client_id
    values['client_secret'] = constant.api_client_secret
    ccl_server = server.CclServer(url, values)
    
    try:
        response = ccl_server.send_post()
        response  = response.replace("\"","'")
        response_dict = eval(response);
        if response_dict.has_key("access_token"):#get is success
            access_token = unicode(response_dict['access_token'], 'gbk')
            user_access_tokens[username] = datetime.datetime.now(),access_token #有效的access_token加入缓存
            print "get access_token is success!"
        else:
            print "get access_token is failed",unicode(response_dict['error_description'], 'gbk')
    except Exception as err:
        print err;
        
    return access_token;

if __name__ =="__main__":
    print get_access_token("test100","111111"); 
    print get_access_token("test100","111111"); 
    pass